package com.cdbkj.cloud.pos;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.XXX.socialsecuritycard.impl.ISocialSecurityInterface;
import com.androidyang.library.common.utils.GsonUtils;
import com.androidyang.library.http.okhttp.bean.HttpResult;
import com.androidyang.library.http.okhttp.listener.HttpClientHandler;
import com.cdbkj.cloud.pos.bean.Filed;
import com.cdbkj.cloud.pos.bean.PrintModel;
import com.cdbkj.cloud.pos.fragment.DoctorFragment;
import com.cdbkj.cloud.pos.fragment.IdentificationFragment;
import com.cdbkj.cloud.pos.fragment.MedicalCardFragment;
import com.cdbkj.cloud.pos.fragment.PayWayFragment;
import com.cdbkj.cloud.pos.fragment.PrescriptionFragment;
import com.cdbkj.cloud.pos.fragment.PrescriptionInfoFragment;
import com.cdbkj.cloud.pos.fragment.UnPayRegisterFragment;
import com.cdbkj.cloud.pos.fragment.WarnFragment;
import com.cdbkj.cloud.pos.http.HttpRequest;
import com.cdbkj.cloud.pos.utils.HardwareUtil;
import com.cdbkj.cloud.pos.utils.Tools;
import com.cdbkj.cloud.pos.bean.JsonResult;
import com.cdbkj.cloud.pos.fragment.BankCardFragment;
import com.dawn.cloud.pos.drive.sdk.BmpSdk;
import com.dawn.cloud.pos.drive.sdk.CLSdk;
import com.dawn.cloud.pos.drive.sdk.PrintSdk;
import com.orhanobut.logger.Logger;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


/**
 * 处方缴费
 */
public class PrescriptionActivity extends AppCompatActivity
        implements PrescriptionFragment.OnPrescriptionFragmentInteractionListener,
        IdentificationFragment.OnIdentificationFragmentInteractionListener,
        PayWayFragment.OnPayWayFragmentInteractionListener,
        BankCardFragment.OnBankCardFragmentInteractionListener,
        MedicalCardFragment.OnMedicalCardFragmentInteractionListener,
        View.OnClickListener, HttpClientHandler {

    private PrescriptionActivity activity = this;

    private ImageView homeImage;

    private Runnable handelBizRunnable = null;
    private Runnable retentionRunnable = null;//页面滞留时间进程
    //private int retentionTime = Filed.retentionTime;//页面滞留时间
    private int readCardTime = Filed.readCardTime;//读卡间隔时间

    private String userId = Tools.getAndroidOsSystemProperties();//产品sn作为序列号
    private String patientId = "";
    private String cardTypeId = "1";
    private String cardNo = "";
    private String prescriptionSeq;
    private String prescriptionFee;
    private String tranFlow;
    private String httpType;
    private String orderNumber;

    private TextView textView_identification;
    private TextView textView_prescription;
    private TextView textView_unPay_reg;
    private TextView textView_textView_payWay;
    private TextView retentionTime_tv;

    private BmpSdk bmpSdk;
    private Timer timer = new Timer();
    int num=0;
    //配对蓝牙名称
    private String bluetoothName;
    //配对款台号
    private String counterNo;

    private String hisTime;

    private String pwd = "";

    private BankCardFragment bankCardFragment;

    private boolean isFinish = false;
    //是否支付中
    private boolean isPaying = false;

    private AlertDialog alertDialog1 = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prescription);

        // 获取意图对象
        Intent intent = getIntent();
        //获取传递的值
        bluetoothName = intent.getStringExtra("bluetoothName");
        counterNo = intent.getStringExtra("counterNo");
        hisTime = intent.getStringExtra("hisTime");

        TextView textBtn = findViewById(R.id.returnBtn);
        homeImage = findViewById(R.id.home_btn);
        homeImage.setOnClickListener(this);
        textBtn.setOnClickListener(this);

        textView_unPay_reg = findViewById(R.id.reg_unPay);
        textView_identification = findViewById(R.id.identification_tab);
        textView_prescription = findViewById(R.id.prescription_tab);
        textView_textView_payWay = findViewById(R.id.select_pay_way);

        textView_identification.setActivated(true);

        retentionTime_tv = findViewById(R.id.retentionTime_tv);
        retentionTime_tv.setText((Filed.retentionTime / 1000) + " 秒");

        //进入第一个界面 身份识别
        getSupportFragmentManager().beginTransaction().replace(R.id.prescription_contentPanel, IdentificationFragment.newInstance()).addToBackStack(null).commit();
        final PrescriptionActivity prescriptionActivity = this;
        this.getPatientId(prescriptionActivity);
        //  this.onIdentificationFragmentInteraction();
    }


    /**
     * 进入 第4个界面 处方详情
     *
     * @param prescriptionDate
     * @param prescriptionSeq
     */
    @Override
    public void onPrescriptionFragmentInteraction(String prescriptionDate, String prescriptionSeq) {
        getSupportFragmentManager().beginTransaction().replace(R.id.prescription_contentPanel, PrescriptionInfoFragment.newInstance(prescriptionDate, prescriptionSeq, userId)).addToBackStack(null).commit();
        this.handelRetention(this, "");
    }

    /**
     * 进入 第4个界面 选择支付方式
     *
     * @param prescriptionSeq
     * @param cost
     */
    @Override
    public void toPayWay(String prescriptionSeq, String cost) {
        this.prescriptionSeq = prescriptionSeq;
        this.prescriptionFee = cost;
        textView_textView_payWay.setActivated(true);
        getSupportFragmentManager().beginTransaction().replace(R.id.prescription_contentPanel, PayWayFragment.newInstance(null, null)).addToBackStack(null).commit();
        this.handelRetention(this, "");
    }

    @Override
    public void onPayWayFragmentInteraction(String type) {
        isPaying = true;
        if ("bank_card".equals(type)) {
            //进入银行卡支付
            bmpSdk = new BmpSdk();
            bankCardFragment = BankCardFragment.newInstance(userId, prescriptionFee, bluetoothName, counterNo);
            bankCardFragment.setBmpSdk(bmpSdk);
            getSupportFragmentManager().beginTransaction().replace(R.id.prescription_contentPanel, bankCardFragment).addToBackStack(null).commit();
        } else if ("medical_card".equals(type)) {
            //进入第6_2个界面 医保卡支付
            getSupportFragmentManager().beginTransaction().replace(R.id.prescription_contentPanel, MedicalCardFragment.newInstance(null, null)).addToBackStack(null).commit();
            //处理医保卡交易及调用读卡器驱动
            //  this.onMedicalCardFragmentInteraction(pwd);
        } else if ("scan_qrcode".equals(type)) {
            httpType = "addPrescriptionOrder";
            HttpRequest.addPrescriptionOrder("addPrescriptionOrder", this, prescriptionSeq, "1", cardNo, userId);
        }

        this.handelRetention(activity, "");
    }

    @Override
    public void onBankCardFragmentInteraction(String posTransNo, String openBank, String openAccount) {
        httpType = "modifyPrescription";
        HttpRequest.modifyPrescription("modifyPrescription", this, userId, prescriptionSeq, patientId, cardTypeId, cardNo, "银行卡支付", "4", posTransNo, openBank, openAccount);
    }


    @Override
    public void returnSelectPayWay() {
        this.toPayWay(prescriptionSeq, prescriptionFee);
    }

    @Override
    public void onBankCardRescissionInteraction(String status) {
        httpType = "modifyPrescriptionRescissionStatus";
        HttpRequest.modifyPrescriptionRescissionStatus("modifyPrescriptionRescissionStatus", this, status, prescriptionSeq);
    }

    @Override
    public void onMedicalCardFragmentInteraction(String pwd, FragmentActivity activity) {
        String result = readMedicalCard(pwd);
        if (result == "" || result.equals("fail")) {
            return;
        }
        Tools.alertDialog("医保结算中...", this);
        if (result.length() > 20) {
            httpType = "httpYB";
            HttpRequest.YBHttp("modifyPrescriptionWithYb", this, tranFlow, prescriptionSeq, cardTypeId, patientId, userId, result);
        }
    }

    @Override
    public void onClick(View view) {
        if (handelBizRunnable != null) {
            textView_identification.removeCallbacks(handelBizRunnable);
        }
        if (retentionRunnable != null) {
            homeImage.removeCallbacks(retentionRunnable);
        }
        if (bmpSdk != null) {
            bmpSdk.shutdownClient();
            //解除广播
            unregisterReceiver(bmpSdk);
            bmpSdk = null;
        }
        switch (view.getId()) {
            case R.id.returnBtn:
                if (isPaying) {
                    return;
                }
                FragmentManager fragmentManager = getSupportFragmentManager();
                int backStackEntryCount = fragmentManager.getBackStackEntryCount();
                if (isFinish) {
                    finish();
                } else if (backStackEntryCount == 5) {
                    fragmentManager.popBackStack();
                } else if (backStackEntryCount == 4) {
                    textView_textView_payWay.setActivated(false);
                    fragmentManager.popBackStack();
                } else if (backStackEntryCount == 3) {
                    textView_prescription.setActivated(false);
                    fragmentManager.popBackStack();
                } else {
                    finish();
                }
                break;
            case R.id.home_btn:
                if (isPaying) {
                    return;
                }
                /*Intent intent = new Intent(this,MainActivity.class);
                startActivity(intent);*/
                Tools.returnMainActivity(this);
                break;
        }
    }

    /**
     * 处理页面滞留
     */
    public void handelRetention(final PrescriptionActivity activity1, final String msg) {
        if (retentionRunnable != null) {
            homeImage.removeCallbacks(retentionRunnable);
        }
        Tools.retentionTime = Filed.retentionTime;//重置 页面滞留时间
        retentionRunnable = new Runnable() {
            @Override
            public void run() {
                while (Tools.retentionTime <= 0) {
                    isPaying = false;
                    if (!"".equals(msg)) {
                        Tools.showDialogWithReturnMainActivity(msg, activity1);
                    }
                    homeImage.removeCallbacks(handelBizRunnable);
                    if (handelBizRunnable != null) {
                        homeImage.removeCallbacks(handelBizRunnable);
                    }
                    ImageView home_btn = findViewById(R.id.home_btn);
                    home_btn.performClick();
                    return;
                }
                Tools.retentionTime -= 1000;
                retentionTime_tv.setText(Tools.retentionTime / 1000 + " 秒");
                //每1秒执行一次
                homeImage.postDelayed(this, 1000);
            }
        };
        homeImage.postDelayed(retentionRunnable, 0);
    }

    @Override
    public void httpClientSuccess(Object o, HttpResult httpResult) {
        JsonResult json = (JsonResult) httpResult.getResult();
        if (json == null) {
            //ToastUtils.showShort(this,"服务器处理异常");
            Tools.showDialogWithReturnMainActivity("服务器处理异常", this);
        }
      /*  if("patientInfo".equals(httpType)){
            Map resultMap = (Map)json.getData();
            if(resultMap.get("patientId")==null){
                //ToastUtils.showShort(this,"HIS数据错误，无病人ID");
                Tools.showDialogWithReturnMainActivity("HIS数据错误，无病人ID",this);
                return;
            }
            patientId = resultMap.get("patientId").toString();
            //跳转待缴费处方列表
            getSupportFragmentManager().beginTransaction().replace(R.id.prescription_contentPanel, PrescriptionFragment.newInstance(patientId,userId)).addToBackStack(null).commit();
            textView_prescription.setActivated(true);
            this.handelRetention(this,"");
        }*/
        //进入 第2个界面 待缴费处方列表
        if ("patientInfo".equals(httpType)) {

            if (!json.isSuccess()) {
                //ToastUtils.showShort(this,json.getMsg());
                Tools.showDialogWithReturnMainActivity(json.getMsg(), this);
                return;
            }
            Map resultMap = (Map) json.getData();
            if (resultMap.get("patientId") == null) {
                //ToastUtils.showShort(this,"HIS数据错误，无病人ID");
                Tools.showDialogWithReturnMainActivity("HIS数据错误，无病人ID", this);
                return;
            }
            patientId = resultMap.get("patientId").toString();
            //跳转待缴费处方列表
            getSupportFragmentManager().beginTransaction().replace(R.id.prescription_contentPanel, PrescriptionFragment.newInstance(patientId, userId)).addToBackStack(null).commit();
            textView_unPay_reg.setActivated(true);
            this.handelRetention(this, "");
        } else if ("addPrescriptionOrder".equals(httpType)) {

            if (!json.isSuccess()) {
                //ToastUtils.showShort(this,json.getMsg());
                Tools.showDialogWithReturnMainActivity(json.getMsg(), this);
                return;
            }
            orderNumber = (String) json.getData();
            //String imgUrl = HttpUrls.QRCODE_PATH+"/"+Filed.wx_app_id+"/"+orderNumber+"/"+new Double(Double.parseDouble(regInfoForm.getTotalCost())*100).longValue()+"/挂号支付";
            Tools.showImgDialog("请用微信扫-扫", HttpRequest.getQRCodeUrl(orderNumber, Double.parseDouble(prescriptionFee), "处方缴费"), this);
            this.handelRetention(this, "");

            //查询订单支付状态
            handelBizRunnable = new Runnable() {
                @Override
                public void run() {
                    httpType = "wxOrderPayStatus";
                    HttpRequest.getWxOrderPayStatus("wxOrderPayStatus", activity, orderNumber);
                    textView_identification.postDelayed(handelBizRunnable, 5000);
                }
            };
            textView_identification.postDelayed(handelBizRunnable, 5000);
        } else if ("wxOrderPayStatus".equals(httpType)) {

            if (!json.isSuccess()) {
                //ToastUtils.showShort(this,json.getMsg());
                Tools.showDialogWithReturnMainActivity(json.getMsg(), this);
                return;
            }
            Map resultMap = (Map) json.getData();
            if (resultMap.get("trade_state") != null && "SUCCESS".equals(resultMap.get("trade_state").toString())) {
                textView_identification.removeCallbacks(handelBizRunnable);
                Tools.dismissImgDialog();
                //更新订单支付状态
                httpType = "modifyOrder";
                HttpRequest.modifyPrescriptionOrderPayStatus("modifyPrescriptionOrderPayStatus", activity, orderNumber);
            }
        } else if ("modifyOrder".equals(httpType) || "modifyPrescription".equals(httpType)) {
            isFinish = true;
            if (!json.isSuccess()) {
                //ToastUtils.showShort(this,json.getMsg());
                //Tools.showDialog(json.getMsg(),this);
                if ("modifyOrder".equals(httpType)) {
                    httpType = "refundWxOrder";
                    HttpRequest.refundWxOrder("refundWxOrder", activity, orderNumber, Double.parseDouble(prescriptionFee));
                    Tools.showDialog("费用已经退回到您的微信！（挂号失败，原因：" + json.getMsg() + "）", this);
                } else if ("modifyPrescription".equals(httpType)) {
                    bankCardFragment.rescission();
                }
                return;
            }
            Map resultMap = (Map) json.getData();
            String tranFlow = "";
            String sendWin = "";
            String tranTime = "";
            if (resultMap.get("tranFlow") != null) {
                tranFlow = resultMap.get("tranFlow").toString();
            }
            if (resultMap.get("sendWin") != null) {
                sendWin = resultMap.get("sendWin").toString();
            }

            if (resultMap.get("tranTime") != null) {
                tranTime = resultMap.get("tranTime").toString();
            }

            //跳转成功
            getSupportFragmentManager().beginTransaction().replace(R.id.prescription_contentPanel, WarnFragment.newInstance("处方缴费成功，谢谢您的使用！")).addToBackStack(null).commit();
            //打印挂号单据
            //HardwareUtil.pintReg(MapUtil.objectToMap(regInfoForm));
            List<PrintModel> list = new ArrayList<>();
            //list.add(new PrintModel("流水号",tranFlow));
            list.add(new PrintModel("处方号", prescriptionSeq));
            list.add(new PrintModel("流水号", tranFlow));
            list.add(new PrintModel("交易时间", tranTime));
            list.add(new PrintModel("发药窗口", sendWin));
            list.add(new PrintModel("金额", prescriptionFee + " 元"));

            String receiptType = Filed.RECEIPT_TYPE_PAY_RECIPE;
            String title = "会泽县人民医院";
            String regDate = hisTime;
            PrintSdk.print(list, receiptType, title, regDate, patientId, "缴费成功");
        } else if ("httpYB".equals(httpType)) {
               if (json.getCode()!=1) {
                //医保结算失败 没扣钱
                Tools.showDialogWithReturnMainActivity("医保结算失败", this);
            }
            String data = (String) json.getData();
            String[] strs = data.split("\"");
            String fyzh = strs[3];
            String fphm = strs[7];
            String ybjsbh = strs[11];
            //医保调用成功向his发送处方更新请求
            //1、调用医保卡支付处理方法
            Map resultArgs = HardwareUtil.handelMedicalInsuranceCard(prescriptionFee);
            String siOutput = resultArgs.get("siOutput").toString();
            String siInputInfo = resultArgs.get("siInputInfo").toString();
            String siPatientInfo = resultArgs.get("siPatientInfo").toString();
            //2、处理支付信息
            httpType = "modifyPrescriptionWithYb";
            HttpRequest.modifyPrescriptionWithYb("modifyPrescriptionWithYb", this, userId, cardTypeId, cardNo, prescriptionSeq, patientId, siOutput, siInputInfo,fyzh,ybjsbh,fphm, siPatientInfo);
        } else if ("modifyPrescriptionWithYb".equals(httpType)){
            if(json.isNotSuccess()){
                //医保已缴费，处方更新状态失败，打印凭条退款
                List<PrintModel> list = new ArrayList<>();
                //list.add(new PrintModel("流水号",tranFlow));
                list.add(new PrintModel("处方号", prescriptionSeq));
                list.add(new PrintModel("状态", "失败"));
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String payTime = sdf.format(date);
                list.add(new PrintModel("交易时间", payTime));
                list.add(new PrintModel("缴费方式", "市医保"));
                list.add(new PrintModel("金额", prescriptionFee + " 元"));
                String receiptType = Filed.RECEIPT_TYPE_PAY_RECIPE;
                String title = "会泽县人民医院";
                String regDate = hisTime;
                PrintSdk.print(list, receiptType, title, regDate, patientId, "缴费成功");
                Tools.showDialogWithReturnMainActivity("处方缴费失败", this);
                return;
            }
            Map resultMap = (Map) json.getData();
            String tranFlow = "";
            String sendWin = "";
            String tranTime = "";
            if (resultMap.get("tranFlow") != null) {
                tranFlow = resultMap.get("tranFlow").toString();
            }
            if (resultMap.get("sendWin") != null) {
                sendWin = resultMap.get("sendWin").toString();
            }

            if (resultMap.get("tranTime") != null) {
                tranTime = resultMap.get("tranTime").toString();
            }

            //跳转成功
            getSupportFragmentManager().beginTransaction().replace(R.id.prescription_contentPanel, WarnFragment.newInstance("处方缴费成功，谢谢您的使用！")).addToBackStack(null).commit();
            //打印挂号单据
            //HardwareUtil.pintReg(MapUtil.objectToMap(regInfoForm));
            List<PrintModel> list = new ArrayList<>();
            //list.add(new PrintModel("流水号",tranFlow));
            list.add(new PrintModel("处方号", prescriptionSeq));
            list.add(new PrintModel("流水号", tranFlow));
            list.add(new PrintModel("交易时间", tranTime));
            list.add(new PrintModel("发药窗口", sendWin));
            list.add(new PrintModel("金额", prescriptionFee + " 元"));

            String receiptType = Filed.RECEIPT_TYPE_PAY_RECIPE;
            String title = "会泽县人民医院";
            String regDate = hisTime;
            PrintSdk.print(list, receiptType, title, regDate, patientId, "缴费成功");
        }

    }

    @Override
    public void httpClientError(Object o, HttpResult httpResult) {
        //ToastUtils.showShort(this,"网络异常");
        Tools.showDialogWithReturnMainActivity("网络连接异常，请联系管理员", this);
    }

    private String readMedicalCard(String pwd) {
        for (int i = 0; i < 5; i++) {
            String result = "";
            ISocialSecurityInterface iSocialSecurityInterface = new ISocialSecurityInterface();
            JSONObject jsonObject = new JSONObject();
            int t = iSocialSecurityInterface.load(pwd, 100000, jsonObject);
            if (t == 0) {
                result = GsonUtils.toJson(jsonObject);
                return result;
            }
            try {
                long time = 2000;
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Tools.showDialogWithReturnMainActivity("医保结算超时", activity);
        return "fail";
    }
    //扫码
    public void getPatientId(final PrescriptionActivity PrescriptionActivity) {
        timer = new Timer();
        final TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                EditText editText = findViewById(R.id.getPatientId);
                num++;
                System.out.println("我是扫描线程，我没有停止。。。");
                System.out.println("我是扫描线程，我没有停止。。。");
                System.out.println("我是扫描线程，我没有停止。。。");
                if (num == 35) {
                    num = 0;
                    timer.cancel();
                    cancel();
                }
                try {
                    if (!editText.getText().toString().equals("")) {
                        String patientId = editText.getText().toString();
                        String reg = "[^(a-zA-Z0-9\\\\u4e00-\\\\u9fa5)]";
                        patientId = patientId.replaceAll(reg, "");
                        patientId = patientId.replaceAll("\\(", "");
                        //读取卡号成功后，读取档案信息
                        httpType = "patientInfo";
                        HttpRequest.patientInfo("patientInfo", PrescriptionActivity, patientId, userId);
                        System.out.println(editText.getText());
                        timer.cancel();
                        cancel();
                    }
                } catch (Exception e) {
                    timer.cancel();
                    cancel();
                }
            }
        };
        timer.schedule(timerTask, 500, 1000);
    }

    @Override
    public void onIdentificationFragmentInteraction() {

    }
}
